<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Material;
use App\Models\Message;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class MaterialController extends BaseController
{
    protected $model = Material::class;

    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $input = $request->input();
        $search = ['title' => '', 'start_at' => '', 'end_at' => ''];
        $list = Material::apply($search, $input)
            ->orderBy("id", "desc")
            ->paginate(per_page());
        return $this->paginate($list);
    }

    public function store(Request $request)
    {
        $maxSize = 5;
        $file = $request->file('file');
        if ($file->isValid()){
            //检测图片类型
            $ext = $file->getClientOriginalExtension();
//            if (!in_array(strtolower($ext),$allowed_extensions)){
//                $data['msg'] = "请上传".implode(",",$allowed_extensions)."格式文件";
//                return response()->json($data);
//            }
            //检测图片大小
            if ($file->getClientSize() > $maxSize*1024*1024){
                $data['msg'] = "文件大小限制".$maxSize."M";
                return response()->json($data);
            }
        }else{
            $data['msg'] = $file->getErrorMessage();
            return $this->failed($data['msg']);
        }

        $newFile = "uploads/material/" . date('Ymd') . "_" . time()."_".uniqid().".".$file->getClientOriginalExtension();
        if (Storage::disk('public')->put($newFile, file_get_contents($file->getRealPath() ))){
            Material::create([
                'title' => $file->getClientOriginalName(),
                'file_path' => $newFile
            ]);
            $data = [
                'url'   => Storage::disk('public')->url($newFile)
            ];
            return $this->success($data);
        }
    }


    public function destroy(Request $request)
    {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = \request('ids');
        $arr_id = explode(",", $ids);
        foreach ($arr_id as $id) {
            $model = Material::find($id);
            if (!$model)
                continue;

            $file_path = ltrim($model->file_path, env('APP_URL'));
            Storage::disk('public')->delete($file_path);

            $model->delete();
        }
        return $this->success([]);
    }

}

